//
//  ViewController.m
//  RootAppT
//
//  Created by RayMi on 15/3/11.
//  Copyright (c) 2015年 RayMi. All rights reserved.
//

#import "ViewController.h"
#import "Share.h"
#include <notify.h>

#define DefaultNumber 1.f//默认1秒的频率
#define KeyString @"RecordTime"


@interface ViewController ()<UITextFieldDelegate>
@property (weak, nonatomic) IBOutlet UILabel *recordTimeLabel;
@property (weak, nonatomic) IBOutlet UITextField *textField;
@property (weak, nonatomic) IBOutlet UITextView *helpView;

@property (nonatomic,strong) NSTimer *timer;

@property (nonatomic,strong) NSDateFormatter *formatter;


@end

@implementation ViewController

- (NSDateFormatter *)formatter{
    if (!_formatter) {
        _formatter = [[NSDateFormatter alloc]init];
         [_formatter setTimeZone:[NSTimeZone timeZoneWithAbbreviation:@"CCD"]];
        [_formatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    }
    return _formatter;
}

- (void)resetTimer{
    if (_timer && _timer.valid) {
        [_timer invalidate];
        _timer = nil;
    }
    
    float time = _textField.text.floatValue;
    if (time==0) {
        time = DefaultNumber;
    }
    
    _timer = [NSTimer scheduledTimerWithTimeInterval:time target:self selector:@selector(repeat) userInfo:nil repeats:YES];
    [_timer setFireDate:[NSDate distantFuture]];
}

+ (NSString *)path{
    return @"/Applications/RootAppT.app/recordTime.plist";
}
+ (NSDate *)getRecordDate{
    NSString *path = [self path];
    
    NSDictionary *dic = [NSDictionary dictionaryWithContentsOfFile:path];
    NSTimeInterval interval = [dic[@"date"] doubleValue];
    NSDate *date = [NSDate dateWithTimeIntervalSince1970:interval];
    if (!dic) {//无记录，则获取系统时间
        NSLog(@"未获取到记录的时间，使用系统时间");
        date = [NSDate date];
        [self saveRecordDate:date];
    }
    return date;
}

+ (void)saveRecordDate:(NSDate *)newDate{
    NSString *path = [self path];
    
    NSDictionary *dic = @{@"date":@([newDate timeIntervalSince1970])};
    if ([dic writeToFile:path atomically:YES]) {
        NSLog(@"时间保存成功:%@",dic);
    }
}

//MARK: 插件升级版，废弃此方法
//static void Reboot(CFNotificationCenterRef center, void *observer, CFStringRef name, const void *object, CFDictionaryRef userInfo);

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    
    _textField.text = [NSString stringWithFormat:@"%d",(int )DefaultNumber];
    
    [self updateTimeLabel];
    
//    //修改xib上textView文字不显示的问题
//    for (NSLayoutConstraint *constraint in self.view.constraints) {
//        if (constraint.secondItem == _helpView && constraint.secondAttribute == NSLayoutAttributeBottom) {
//            constraint.constant -= 1;
//            break;
//        }
//    }
    
//MARK: 插件升级版，废弃此方法    CFNotificationCenterAddObserver(CFNotificationCenterGetDarwinNotifyCenter(), NULL, Reboot, CFSTR("com.wg.ff3.time"), NULL, CFNotificationSuspensionBehaviorDeliverImmediately);
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(updateTimeLabel) name:@"UPDATE_TIME_LABEL" object:nil];
    
}

- (void)updateTimeLabel{
    _recordTimeLabel.text = [self.formatter stringFromDate:[ViewController getRecordDate]];
}

- (void)repeat{
    //接收到通知
    NSLog(@"-----------%s-----------",__FUNCTION__);
    
    //发送 DidEnterbackground通知给  捕鱼3 app
    notify_post("com.wg.ff3.DidEnterbackground");
    
    //将系统时间增加4小时
    
    NSDate *oldDate = [ViewController getRecordDate];
    NSLog(@"将要修改的旧时间：%@",oldDate);
    
    double a = oldDate.timeIntervalSince1970;
    
    struct Time oldTime = [Share getTimeWithDate:oldDate];
    
    long b = oldTime.tv.tv_sec;
    
    NSLog(@"a:%ld,b:%ld",(long)a,b);
    
    long addSecond = 4 * 60 * 60;//4小时
    
    oldTime.tv.tv_sec += addSecond;
    
    
    if ([Share resetTime:oldTime]==0) {
        //修改时间成功，刷新界面
        
        NSDate *newDate = [NSDate dateWithTimeIntervalSince1970:oldTime.tv.tv_sec];
        
        NSLog(@"将要修改的新时间：%@",newDate);
        
        [ViewController saveRecordDate:newDate];
        
        [[NSNotificationCenter defaultCenter]postNotificationName:@"UPDATE_TIME_LABEL" object:nil];
        
        //系统时间修改完成后，发送 willEnterForground通知给  捕鱼3 app

        notify_post("com.wg.ff3.willEnterForground");
        
    }
    
    
}

- (IBAction)start:(UIButton *)sender {
    
    if (!sender.selected) {
        [self resetTimer];
        
        [_timer setFireDate:[NSDate date]];
        
        /**
         *  自动点击 获取离线金币“确认键”
         停止修改时间，相应关闭；
         设备依赖SimulatorTouch插件，需要先行安装，否则无效
         */
        notify_post("com.wg.ff3.startAutoClick");
        
    }else{
        [_timer invalidate];
        _timer = nil;
        
        notify_post("com.wg.ff3.stopAutoClick");
        
    }
    
    sender.selected = !sender.selected;
    
}

- (IBAction)recordCurrentTimePressed:(id)sender {
    NSLog(@"-----------%s-----------",__FUNCTION__);

    NSDate *date = [NSDate date];
    
    [ViewController saveRecordDate:date];
    
    [self updateTimeLabel];
    
}

#pragma mark -
- (BOOL)textFieldShouldReturn:(UITextField *)textField{
    [textField resignFirstResponder];
    return YES;
}
@end
